﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebSiteFool.Models;
using System.ServiceModel.Syndication;
using WebSiteFool.Libs;

namespace WebSiteFool.Controllers
{
    public class CommentController : BaseController
    {
        //
        // GET: /Comment/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Comment model)
        {
            model.Id = Guid.NewGuid();
            model.CreateDate = DateTime.UtcNow;
            model.Article = DbWorker.ArticleRepository.GetById(model.Article.Id);
            model.User = DbWorker.UserRespository.Get(m => m.UserName == User.Identity.Name).FirstOrDefault(); ;
            DbWorker.CommentRepository.Insert(model);
            DbWorker.Save();
            return PartialView("_List", DbWorker.CommentRepository.Get(m => m.Article.Id == model.Article.Id));
        }

        public ActionResult List(Guid articleId)
        {
            return PartialView("_List", DbWorker.CommentRepository.Get(m => m.Article.Id == articleId));
        }

        public ActionResult Feed()
        {
            SyndicationFeed feed = new SyndicationFeed();
            IList<SyndicationItem> items = new List<SyndicationItem>();
            var comments = DbWorker.CommentRepository.Get(orderBy: OrderByCreateDateDesc);
            foreach (var item in comments)
            {
                var syndicationItem = new SyndicationItem()
                {
                    Id = item.Id.ToString(),
                    Title = new TextSyndicationContent(item.Article.Title),
                    PublishDate = new DateTimeOffset(item.CreateDate),
                    Content = SyndicationContent.CreateHtmlContent(item.Content)
                };
                syndicationItem.AddPermalink(new Uri(string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, "/Article/Show/" + item.Article.Id + "#" + item.Id)));
                items.Add(syndicationItem);

            }
            feed.Items = items;
            feed.Language = "en-us";
            feed.Title = new TextSyndicationContent("New Comment in TangJing.info - Looking for simple & free...");

            return new RssActionResult(feed);
        }

        private IOrderedQueryable<Comment> OrderByCreateDateDesc(IQueryable<Comment> comments)
        {
            return comments.OrderByDescending(item => item.CreateDate);
        }
    }
}
